import React, { useMemo } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useHistory } from "react-router-dom";
import { Modal } from "antd-mobile";
import "antd-mobile/dist/antd-mobile.css";
export default function CartBar() {
    const cartData = useSelector((state) => state.getIn(["cart", "data"]));
    // console.log(cartData);
    const history = useHistory();
    const dispatch = useDispatch();

    //判断是否需要全选
    const checkedAll = useMemo(() => {
        const index = cartData.findIndex((item) => !item.get("checked"));
        if (!cartData.size) {
            return false;
        }
        return index < 0;
    }, [cartData]);

    //修改全选框的状态值，让列表框跟着变化
    const checkedChange = (ev) => {
        const checked = ev.target.checked;
        // 这样做太慢了
        // cartData.forEach(element => {
        //     if(element.get('checked')!==checked){
        //         dispatch({
        //             type:'cart/modify_cart_goods',
        //             checked:checked,
        //             id:element.get('_id')
        //         })
        //     }
        // });
        dispatch({
            type: "cart/modify_goods_checked",
            checked: checked,
        });
    };

    // 计算总价
    const computed=useMemo(()=>{
        let retailPrice=0;
        let counterPrice=0;
        let count=0
        cartData.forEach(item=>{
            if(item.get('checked')){
                retailPrice+=item.get('count')* item.get("retailPrice");
                counterPrice+=item.get('count')* item.get("counterPrice");
                count+=item.get('count')
            }
        })
        let discountPrice=counterPrice-retailPrice;
        return{retailPrice,discountPrice,count}
    },[cartData])

    // 提交订单
    const submitAction=()=>{
        let goodsArr=[];
         cartData.forEach(element => {
            if(element.get('checked')===true){
                let goodsObj={
                    date:new Date().getTime(),
                    id:element.get('goodsID'),
                    selectedIDs :element.get('selectedIDs'),
                    count:element.get('count'),
                    flag:0
                }
                goodsArr.push(goodsObj);
            }
        });
        dispatch({
            type:'order/submit_order',
            value:goodsArr
        })
        let tip=sessionStorage.getItem('add-cart');
        if(tip){
            Modal.alert("加入成功");
            history.push({pathname:'/order'})
        }
    }

    return (
        <div className="cart-bar">
            <div className="input">
                <input
                    type="checkbox"
                    checked={checkedAll}
                    onChange={checkedChange}
                />
            </div>
            <div className="count">
                <p>已选：{computed.count}件</p>
            </div>
            <div className="price">
                <span>合计：￥{computed.retailPrice}</span>
                <span> 已优惠：￥{computed.discountPrice}</span>
            </div>

            <div className="submit">
                <button onClick={submitAction}>下单</button>
            </div>
        </div>
    );
}
